package com.intel.service 
{
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.display.Sprite;
    import flash.events.*;
    import flash.net.*;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	/**
	 * ...
	 * @author Fintan Boyle
	 * 
	 * example usage:
	 * var service:HttpService = new HttpService();
	 * service.addEventListener(ServiceEvent.RESULT, service_onResult);
	 * service.addEventListener(ServiceEvent.FAULT, service_onFault);
	 * service.method = URLRequestMethod.GET;
	 * service.url = "lo.xml";
	 * service.send();
	 * 
	 */
	public class HttpService extends EventDispatcher 
	{
		private var _url:String;
		private var _method:String = URLRequestMethod.GET;
		private var _data:Object;
		
		public function HttpService(){}
		
		public function send(params:Object=null):void 
		{
			var loader:IEventDispatcher;
			var loader2:Loader;
			
			if (this.url.indexOf(".swf") > -1) {
				
				loader2 = new Loader();
				//configureListeners((loader as Loader).contentLoaderInfo);
				//configureListeners(loader2.contentLoaderInfo);
				configureListeners2(loader2.contentLoaderInfo);
				
				trace("load a swf");
			}else {
				loader = new URLLoader();
				configureListeners(loader as URLLoader);
			}
			
            var request:URLRequest = new URLRequest(this.url);
			
			if (params != null) request.data = params;
			
            try {
                if (this.url.indexOf(".swf") > -1) {
					//(loader as Loader).load(request);
					
					//var ldrContext:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
					//loader2.load(request, ldrContext);
					loader2.load(request);
					trace("load " + this.url);
				}else {
					(loader as URLLoader).load(request);
				}
            } catch (er:Error) {
				error("Unable to load requested document.", null);
				
				removeListeners(loader);
            }
		}
		
		private function configureListeners(dispatcher:IEventDispatcher):void {
            dispatcher.addEventListener(Event.COMPLETE, completeHandler);
            dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
            dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
            dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
        }
		
		private function configureListeners2(dispatcher:LoaderInfo):void {
            dispatcher.addEventListener(Event.COMPLETE, completeHandler);
            dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
            dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
            dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
        }
		
		private function removeListeners(dispatcher:IEventDispatcher):void {
            if (dispatcher != null) {
				
				trace("removeListeners");
				//(dispatcher as Loader).unload();
				
				dispatcher.removeEventListener(Event.COMPLETE, completeHandler);
				dispatcher.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
				dispatcher.removeEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
				dispatcher.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
				
			}
        }

        private function completeHandler(event:Event):void {
			
			trace("loaded! " + this.url);
			
			if (this.url.indexOf(".swf") > -1) {
				
				trace("bytesLoaded " + LoaderInfo(event.target).bytesLoaded);
				trace("bytesTotal " + LoaderInfo(event.target).bytesTotal);
				this.data = event.currentTarget.content;
				
				trace("swf loaded completeHandler");
				
			}else {
				var loader:URLLoader = URLLoader(event.target);
				this.data = loader.data;
			}
			success("successful", event);
        }

        private function securityErrorHandler(event:SecurityErrorEvent):void {
            error("securityErrorHandler: " + event, event);
        }

        private function httpStatusHandler(event:HTTPStatusEvent):void {
            trace("httpStatusHandler: " + event);
        }

        private function ioErrorHandler(event:IOErrorEvent):void {
			error("ioErrorHandler: " + event, event);
        }
		
		private function success(message:String, e:Event):void
		{
			trace("success " + message);
			var successEvent:ServiceEvent = new ServiceEvent(ServiceEvent.RESULT);
			successEvent.message = message;
			successEvent.data = this.data;
			this.dispatchEvent(successEvent);
			removeListeners(e.target as IEventDispatcher);
		}
		private function error(message:String, e:Event):void
		{
			trace("error " + message);
			var errorEvent:ServiceEvent = new ServiceEvent(ServiceEvent.FAULT);
			errorEvent.message = message;
			this.dispatchEvent(errorEvent);
			removeListeners(e.target as IEventDispatcher);
		}
		
		public function get url():String { return _url; }
		
		public function set url(value:String):void 
		{
			_url = value;
		}
		
		public function get method():String { return _method; }
		
		public function set method(value:String):void 
		{
			_method = value;
		}
		
		public function get data():Object { return _data; }
		
		public function set data(value:Object):void 
		{
			_data = value;
		}
		
	}
	
}